<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }"><i class="el-icon-menu"></i> 系统管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-button type="primary" icon="delete" class="handle-del mr10" @click="add">新增</el-button>
            <el-button type="primary" icon="delete" class="handle-del mr10" @click="delAll">批量删除</el-button>
            <el-button type="primary" icon="delete" class="handle-del mr10" @click="resetPassword">重置密码</el-button>
        </div>
        <el-table :data="userList" border style="width: 100%" ref="multipleTable"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column prop="account" label="账号" sortable>
            </el-table-column>
            <el-table-column prop="name" label="姓名">
            </el-table-column>
            <el-table-column prop="sex" label="性别">
            </el-table-column>
            <el-table-column prop="roleNames" label="角色">
            </el-table-column>
            <el-table-column prop="deptName" label="部门">
            </el-table-column>
            <el-table-column prop="email" label="邮箱">
            </el-table-column>
            <el-table-column prop="phone" label="电话">
            </el-table-column>
            <el-table-column prop="createtime" label="创建时间" :formatter="formatDateCreatetime" sortable>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template scope="scope">
                    <span v-if="scope.row.status==1">启用</span>
                    <span v-if="scope.row.status==2">冻结</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template scope="scope">
                    <el-button-group>
                        <el-button size="mini" type="primary"
                                   @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button size="mini" type="primary"
                                   @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                        <template>
                            <span v-if="scope.row.status==1">
                                <el-button size="mini" type="primary"
                                           @click="freeze(scope.$index, scope.row)">用户冻结
                                </el-button>
                            </span>
                            <span v-if="scope.row.status==2">
                                 <el-button size="mini" type="primary"
                                            @click="unfreeze(scope.$index, scope.row)">解除冻结
                                 </el-button>
                            </span>
                        </template>
                        <el-button size="mini" type="primary"
                                   @click="createRole(scope.$index, scope.row)">角色分配
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                @current-change="getData"
                :page-size="size"
                layout="total, prev, pager, next"
                :total="total">
            </el-pagination>
        </div>

        <div>
            <!--新增弹框-->
            <el-dialog title="新增" :visible.sync="addFormVisible">
                <el-form :model="addForm" :inline="true" :rules="rules" ref="addForm" label-position="right"
                         class="demo-form-inline">
                    <el-form-item prop="account" label="账号：" :label-width="formLabeWidth">
                        <el-input v-model="addForm.account" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="name" label="姓名：" :label-width="formLabeWidth">
                        <el-input v-model="addForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="birthday" label="出生日期：" :label-width="formLabeWidth">
                        <el-date-picker type="date" placeholder="选择日期" v-model="addForm.birthday"></el-date-picker>
                    </el-form-item>
                    <el-form-item prop="sex" label="性别：" :label-width="formLabeWidth">
                        <el-radio-group v-model="addForm.sex" size="medium ">
                            <el-radio-button label="男"></el-radio-button>
                            <el-radio-button label="女"></el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="password" label="密码：" :label-width="formLabeWidth">
                        <el-input type="password" v-model="addForm.password" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="repassword" label="确认密码：" :label-width="formLabeWidth">
                        <el-input type="password" v-model="addForm.repassword" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="deptid" label="部门：" :label-width="formLabeWidth">
                        <el-input v-model.number="addForm.deptid" @focus="deptTreeFormVisible=true;">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="邮箱：" :label-width="formLabeWidth">
                        <el-input v-model="addForm.email" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话：" :label-width="formLabeWidth">
                        <el-input v-model="addForm.phone" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addSubmitForm('addForm')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <div>
            <!--编辑弹框-->
            <el-dialog title="编辑" :visible.sync="editFormVisible">
                <el-form :model="editForm" :inline="true" :rules="rules" ref="editForm" label-position="right"
                         class="demo-form-inline">
                    <el-form-item prop="account" label="账号：" :label-width="formLabeWidth">
                        <el-input v-model="editForm.account" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="name" label="姓名：" :label-width="formLabeWidth">
                        <el-input v-model="editForm.name" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="birthday" label="出生日期：" :label-width="formLabeWidth">
                        <el-date-picker type="date" placeholder="选择日期" v-model="editForm.birthday"></el-date-picker>
                    </el-form-item>
                    <el-form-item prop="sex" label="性别：" :label-width="formLabeWidth">
                        <el-radio-group v-model="editForm.sex" size="medium ">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="deptid" label="部门：" :label-width="formLabeWidth">
                        <el-input v-model.number="editForm.deptid" @focus="deptTreeFormVisible=true;"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱：" :label-width="formLabeWidth">
                        <el-input v-model="editForm.email" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="电话：" :label-width="formLabeWidth">
                        <el-input v-model="editForm.phone" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editSubmitForm('editForm')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <el-dialog title="选择部门" :visible.sync="deptTreeFormVisible">
            <el-tree
                :data="deptTreeDatas"
                show-checkbox
                check-strictly
                node-key="id"
                ref="deptTree"
                highlight-current
                lazy
                :expand-on-click-node="false"
                :load="loadNode"
                @node-click="getKey"
                :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deptTreeFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectTree">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="选择角色" :visible.sync="roleTreeFormVisible">
            <el-tree
                show-checkbox
                check-strictly
                node-key="id"
                ref="roleTree"
                highlight-current
                lazy
                :expand-on-click-node="false"
                :load="loadNodeRole"
                :props="roleProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roleTreeFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectRole">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {formatDate} from '../../../static/js/date.js';

    export default {
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.addForm.repassword !== '') {
                        this.$refs.addForm.validateField('repassword');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.addForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var validatePassEdit = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.editForm.repasswordEdit !== '') {
                        this.$refs.editForm.validateField('repasswordEdit');
                    }
                    callback();
                }
            };
            var validatePass2Edit = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.editForm.passwordEdit) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                currentUserId:'',
                del_list: [],
                is_search: false,
                userList: [],
                deptTreeDatas: [],
                addFormVisible: false,
                editFormVisible: false,
                deptTreeFormVisible: false,
                roleTreeFormVisible: false,
                addForm: {
                    account: "",
                    name: "",
                    sex: "",
                    birthday: "",
                    password: "",
                    repassword: "",
                    role: "",
                    deptid: "",
                    email: "",
                    phone: ""
                },
                editForm: {
                    account: "",
                    name: "",
                    sex: "",
                    birthday: "",
                    passwordEdit: "",
                    repasswordEdit: "",
                    role: "",
                    deptid: "",
                    email: "",
                    phone: ""
                },
                formLabeWidth: '100px',
                rules: {
                    account: [
                        {required: true, message: '请输入账号', trigger: 'change'},
                    ],
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'change'}
                    ],
                    sex: [
                        {required: true, message: '请选择性别', trigger: 'change'}
                    ],
                    birthday: [
                        {type: 'date', required: true, message: '请选择出生日期', trigger: 'change'}
                    ],
                    password: [
                        {validator: validatePass, trigger: 'change', required: true}
                    ],
                    repassword: [
                        {validator: validatePass2, trigger: 'change', required: true}
                    ],
                    deptid: [
                        {type: 'number', required: true, message: '请选择部门', trigger: 'change'}
                    ],
                    passwordEdit: [
                        {validator: validatePassEdit, trigger: 'change', required: true}
                    ],
                    repasswordEdit: [
                        {validator: validatePass2Edit, trigger: 'change', required: true}
                    ]
                },
                defaultProps: {
                    children: 'children',
                    label: 'fullname'
                },
                roleProps: {
                    children: 'children',
                    label: 'name'
                },
                total:0 ,
                currentPage: 1,
                size:10
            }
        },
        created() {
            this.getData();
        },
        methods: {
            //获取user数据
            getData(data) {
                let self = this;
                var Vstart=0;
                var Vsize=self.size;
                if(data!=undefined&&!isNaN(data)){
                    Vstart=data-1;
                }
                self.$axios.post("/api/user/get",{pageNumber:Vstart,pageSize:self.size})
                    .then(function (res) {
                        self.userList = res.data.data.content;
                        self.total=res.data.data.totalElements;
                    })
            },
            //新增面板
            add: function () {
                this.addFormVisible = true;
            },
            //添加用户
            addSubmitForm(formName) {
                const self = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //alert('submit!');
                        self.$axios.post('/api/user/add', self.addForm)
                            .then(function (response) {
                                console.log(response);
                                self.$message({
                                    message: "添加成功",
                                    type: 'warning'
                                });
                                self.addFormVisible = false;
                                self.getData();
                            })
                            .catch(function (error) {
                                if (error.response) {
                                    // 请求已发出，但服务器响应的状态码不在 2xx 范围内
                                    self.$message({
                                        message: error.response.data.msg,
                                        type: 'error'
                                    });
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //修改用户
            editSubmitForm(formName) {
                const self = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //alert('submit!');
                        self.$axios.put('/api/user/update', self.editForm)
                            .then(function (response) {
                                console.log(response);
                                self.$message({
                                    message: "修改成功",
                                    type: 'warning'
                                });
                                self.editFormVisible = false;
                                self.getData();
                            })
                            .catch(function (error) {
                                if (error.response) {
                                    // 请求已发出，但服务器响应的状态码不在 2xx 范围内
                                    self.$message({
                                        message: error.response.data.msg,
                                        type: 'error'
                                    });
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            formatDateCreatetime(data, row) {
                if (data.createtime != null) {
                    return formatDate(new Date(data.createtime), 'yyyy-MM-dd hh:mm');
                }
            },
            //编辑面板
            handleEdit(index, row) {
                const self = this;
                console.log(row);
                //self.$message('编辑第'+(index+1)+'行');
                self.editForm = row;
                self.editFormVisible = true;
            },
            //删除用户
            handleDelete(index, row) {
                const self = this;
                //self.$message.error('删除第'+(index+1)+'行');
                console.log(row.id);
                self.$confirm('确认删除吗？', '提示', {
                    type: 'warning'
                }).then(function () {
                    self.$axios.delete('/api/user/delete/' + row.id)
                        .then(function (response) {
                            console.log(response);
                            self.$message({
                                message: "删除成功",
                                type: 'warning'
                            });
                            self.getData();
                        })
                        .catch(function (error) {
                            if (error.response) {
                                // 请求已发出，但服务器响应的状态码不在 2xx 范围内
                                self.$message({
                                    message: error.response.data.msg,
                                    type: 'error'
                                });
                            }
                        })
                })
            },
            //冻结用户
            freeze(index, row) {
                const self = this;
                self.$axios.put('/api/user/freeze/' + row.id)
                    .then(function (response) {
                        console.log(response);
                        self.$message({
                            message: "冻结成功",
                            type: 'warning'
                        });
                        self.getData();
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            //解除冻结
            unfreeze(index, row) {
                const self = this;
                self.$axios.put('/api/user/unfreeze/' + row.id)
                    .then(function (response) {
                        console.log(response);
                        self.$message({
                            message: "解除冻结成功",
                            type: 'warning'
                        });
                        self.getData();
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            //树形部门加载
            loadNode: function (node, addNode) {
                const self = this;
                var pid;
                if (node.id == 0) {
                    pid = 0;
                } else {
                    pid = node.data.id;
                }
                this.$axios.get('/api/dept/selectDeptTreeList/' + pid)
                    .then(function (data) {
                        addNode(data.data.data);
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            getKey: function (data, node) {
                console.log(data);
            },
            //选择部门
            selectTree: function () {
                const self = this;
                var depts = self.$refs.deptTree.getCheckedNodes();
                if (depts.length == 0) {
                    self.$message.error('请选择一项！');
                    return;
                }
                if (depts.length > 1) {
                    self.$message.error('只能选择一项！');
                    return;
                }
                console.log(depts);
                self.addForm.deptid = depts[0].id;
                self.editForm.deptid = depts[0].id;
                self.deptTreeFormVisible = false;
            },
            //树形角色加载
            loadNodeRole: function (node, addNode) {
                const self = this;
                var pid;
                if (node.id == 0) {
                    pid = 0;
                } else {
                    pid = node.data.id;
                }
                this.$axios.get('/api/role/selectRoleTreeList/' + pid)
                    .then(function (data) {
                        addNode(data.data.data);
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            //打开树形角色选择面板
            createRole:function(index, row){
                const self = this;
                self.roleTreeFormVisible=true;
                self.currentUserId=row.id;
            },
            //角色分配
            selectRole: function () {
                const self = this;
                var roles = self.$refs.roleTree.getCheckedNodes();
                if (roles.length == 0) {
                    self.$message.error('请至少选择一项！');
                    return;
                }
                var rolesIdStr="";
                for(var i=0;i<roles.length;i++){
                    rolesIdStr+=roles[i].id+",";
                }
                console.log(rolesIdStr);
                self.$axios.post('/api/user/setRole/' + self.currentUserId,{roleid:rolesIdStr})
                    .then(function (data) {
                        self.$message({
                            message: "删除成功",
                            type: 'warning'
                        });
                        self.getData();
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
                self.roleTreeFormVisible= false;
            },
            //批量删除
            delAll() {
                const self = this,
                    length = self.multipleSelection.length;
                let str = '';
                self.del_list = self.del_list.concat(self.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += self.multipleSelection[i].name + ' ';
                }
                self.$message.error('删除了' + str);
                self.multipleSelection = [];
            },
            //重置密码
            resetPassword() {
                const self = this,
                    length = self.multipleSelection.length;
                if (length == 0) {
                    self.$message.error('请选择一项！');
                    return;
                }
                if (length > 1) {
                    self.$message.error('只能选择一项！');
                    return;
                }
                self.$axios.post('/api/user/resetPassword/' + self.multipleSelection[0].id)
                    .then(function (data) {
                        self.$message({
                            message: "重置成功",
                            type: 'warning'
                        });
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    });
                self.multipleSelection = [];
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            }
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
</style>
